package com.hzx.zhihu.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

public class ImageSimilarityUtil {

    // 计算图片的均值哈希值
    public static String calculateAverageHash(InputStream imageStream) throws IOException {
        // 1. 读取图片并缩小为8x8
        BufferedImage image = ImageIO.read(imageStream);
        BufferedImage resizedImage = new BufferedImage(8, 8, BufferedImage.TYPE_INT_RGB);
        resizedImage.getGraphics().drawImage(
                image.getScaledInstance(8, 8, Image.SCALE_SMOOTH),
                0, 0, null
        );

        // 2. 转为灰度图
        int[] pixels = new int[8 * 8];
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                int rgb = resizedImage.getRGB(j, i);
                int gray = (int) (0.299 * ((rgb >> 16) & 0xFF) +
                        0.587 * ((rgb >> 8) & 0xFF) +
                        0.114 * (rgb & 0xFF)); // RGB转灰度公式
                pixels[i * 8 + j] = gray;
            }
        }

        // 3. 计算平均灰度值
        int average = 0;
        for (int pixel : pixels) {
            average += pixel;
        }
        average /= 64;

        // 4. 生成哈希值（1或0）
        StringBuilder hash = new StringBuilder();
        for (int pixel : pixels) {
            hash.append(pixel >= average ? "1" : "0");
        }
        return hash.toString();
    }

    // 计算两个哈希值的汉明距离（值越小越相似）
    public static int hammingDistance(String hash1, String hash2) {
        if (hash1.length() != hash2.length()) {
            throw new IllegalArgumentException("哈希值长度必须一致");
        }
        int distance = 0;
        for (int i = 0; i < hash1.length(); i++) {
            if (hash1.charAt(i) != hash2.charAt(i)) {
                distance++;
            }
        }
        return distance;
    }

    // 判断是否相似（汉明距离阈值可根据需求调整，一般≤5认为相似）
    public static boolean isSimilar(String hash1, String hash2, int threshold) {
        return hammingDistance(hash1, hash2) <= threshold;
    }
}